from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.decorators import action
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from users.models import User
from . import serializers
from . import constants
from meiduo_mall.utils.permissions import IsOwner
from goods.models import SKU
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.


# 自定义登录视图
class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        """保留父类验证登录并合并购物车"""
        # 调用父类处理验证登录的业务逻辑
        response = super(UserAuthorizeView, self).post(request, *args, **kwargs)
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            # 调用合并购物车的方法
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        return response

# /browse_histories/
class UserBrowseHistory(CreateModelMixin, GenericAPIView):
    """用户浏览记录"""
    # 验证用户是否登录
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = serializers.AddUserBrowseHistory

    def post(self, request):
        return self.create(request)

    # 因为还要在这个接口实现浏览记录的查询， 所以不能使用CreateAPIView
    def get(self, request):
        """查询用户浏览记录"""
        # 获取用户id
        user_id = request.user.id
        # 创建连接到redis数据库
        redis_conn = get_redis_connection('history')
        # 查询出所有的sku_ids
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)
        # 遍历， 取出所有的sku_id， 查询
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 序列化输出sku
        serializer_sku = SKUSerializer(sku_list, many=True)
        # 返回序列化之后的json数据
        return Response(serializer_sku.data)



# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
# 邮箱验证
class VerifyEmailView(APIView):
    def get(self, request):
        # 获取前端发送过来的token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        # 验证token， 返回user
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message': '无效的token'}, status=status.HTTP_400_BAD_REQUEST)
        # 修改user的email_active属性为true
        user.email_active = True
        user.save()

        return Response({'message': 'OK'})


# 更新邮箱
class EmailView(UpdateAPIView):
    """由于路由的不同， 无法获取pk， 所以也需要重写get_object方法"""

    # 指定序列化器
    serializer_class = serializers.EmailSerializer
    # 使用jwt验证用户是否已登录
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 提供用户的详情
class UserDetailView(RetrieveAPIView):
    """重写get_object方法， 返回当前谁是登录用户"""

    # 指定序列化器
    serializer_class = serializers.UserDetailSerializer

    # IsAuthenticated是采用jwt验证
    # 用来验证用户是否已经登录
    permission_classes = [IsAuthenticated]

    def get_object(self):
        # 重写的原因：是因为路由没有主键， 返回的user是jwt验证系统验证后的用户
        return self.request.user


# url(r'^users/$', views.UserView.as_view()),
# 用户注册
class UserView(CreateAPIView):
    serializer_class = serializers.CreateUserSerializer


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
# 判断手机收是否存在
class MobileCountView(APIView):
    """校验手机号数量"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    '''
    通过用户名数量判断用户是否已经注册
    '''

    def get(self, request, username):
        # 获取指定用户名的数量
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }
        return Response(data)


# 用户中心个人地址
class ADDressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    """用户地址的新增与修改"""
    # 指定序列化器
    serializer_class = serializers.UserADDressSerializer
    # JWT验证用户是否登录
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # 用户地址所有数据(列表)
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    # 保存用户地址
    def create(self, request, *args, **kwargs):
        # 检查用户地址数据不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({
                'message': '保存数据已经到达上限'
            }, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # 删除处理（逻辑删除）
    def destroy(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # 设置默认地址
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        address = self.get_object()
        request.user.default_address = address
        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # 修改标题
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        address = self.get_object()
        # 修改需要在前面加上instance
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class ChangePasswordView(UpdateAPIView):
    """
    用户密码
    """
    queryset = User.objects.all()
    permission_classes = [IsOwner]
    serializer_class = serializers.ChangePasswordSerializer
